package com.example.myapplication.view;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ListViewActivity extends Activity {
    private ListView listView;
    private MapAdapter adapter;
    Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_list);
        initView();
        initEvent();
        List<HashMap> listMap = new ArrayList();
        HashMap e = new HashMap();
        e.put("name", "张三");
        listMap.add(e);
        initData(listMap);
        refresh();

    }

    private void initData(List data) {

        adapter.setData((List<HashMap>)data);

    }

    private void initEvent() {
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Toast.makeText(this,(String) adapter.getItem(position).get("name"), Toast.LENGTH_SHORT).show();
        });
    }


    private void initView() {
        listView = findViewById(R.id.list_view);
        adapter = new MapAdapter(this, R.layout.my_text_view);
        listView.setAdapter(adapter);
    }

    private void refresh() {
        Runnable name = new Runnable() {
            @Override
            public void run() {
                List data = adapter.getData();
                if (data == null) {
                    data = new ArrayList();
                }
                HashMap map = new HashMap();
                map.put("name", "张三" + data.size() + 1);
                data.add(map);
                adapter.setData(data);
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(name,1000);

    }

}
